<template>
  <div class="statistics-container">
    <h1 id="inActiveTime" style="display: none;" />

    <div class="filter-table-view">
      <el-form  ref="filterForm" :inline="true"  v-show="showSearch">
        <el-form-item label="提交编号" prop="serialNumber">
          <el-input v-model="queryParams.serialNumber" placeholder="请输入提交编号" size="small" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="queryProjectResult">查询</el-button>
          <el-button type="warning" icon="el-icon-share" @click="conditionFilterHandle" v-if="projectItemList.length>0">条件</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="result-table-view">
      <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>
          <div class="top-right-btn">
          <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
            <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button size="mini" circle icon="el-icon-refresh" @click="queryProjectResult()" />
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="显隐列" placement="top"  v-if="projectItemList.length>0">
            <el-button size="mini" circle icon="el-icon-menu" @click="customColumnDialogVisible = true" />
          </el-tooltip>
          </div>
      </el-row>

      <!-- 发起问卷弹窗 -->
      <el-dialog :title="formResultWriteTitle"  :visible.sync="formResultWriteOpen" append-to-body>
        <FormResultAdd
          v-if="projectConfig.projectId&&formResultWriteType==='addFormResult'"
          :key="projectConfig.projectId+new Date()"
          :project-config="projectConfig"
          @submit="saveFormProjectResult"
        />

        <FormResultEdit
          v-if="projectUpdateConfig.projectId&&formResultWriteType==='editFormResult'"
          :key="projectUpdateConfig.projectId+new Date()"
          :project-config="projectUpdateConfig"
          @submit="updateFormProjectResult"
        />


        <FormResultEdit
          v-if="projectViewConfig.projectId&&formResultWriteType==='viewFormResult'"
          :key="projectViewConfig.projectId+new Date()"
          :project-config="projectViewConfig"
          @submit="viewFormProjectResult"
        />
      </el-dialog>

      <el-table
        ref="multipleTable"
        :stripe="true"
        :data="projectResultList"
        header-cell-class-name="data-table-header"
        @selection-change="handleSelectionChange"
        @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}"
      >
        <el-table-column type="selection" align="center"/>
        <el-table-column
          v-for="col in fixedCustomColumns" :key="`t${col}`"
          :label="fixedDefaultLabelFormColumn[col]"
        >
          <template slot-scope="scope">
            {{ scope.row[col] }}
          </template>
        </el-table-column>

        <el-table-column
          v-for="col in otherCustomColumns"
          :key="col" :label="projectItemColumns[col]"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row['processDataMap'][col] }}
          </template>
        </el-table-column>

        <el-table-column
          v-for="col in fixedFormTailColumns" :key="`t${col}`"
          :label="fixedDefaultLabelFormTailColumn[col]"
        >
          <template slot-scope="scope">
            {{ scope.row[col] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view"  @click="handleView(scope.row)">详情</el-button>

          <el-button size="mini" type="text" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>

          <el-button size="mini" type="text" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>

        </template>
        </el-table-column>
      </el-table>
      <div>
        <pagination v-show="total>0"  :total="total" background  :page.sync="queryParams.page" :limit.sync="queryParams.rows" @pagination="queryProjectResult"/>
      </div>
    </div>
    <div class="custom-col-container">
      <el-dialog :modal="false"  :visible.sync="customColumnDialogVisible" center title="自定义显示列">
        <el-row>
          <el-col :span="3">
            <span>显示列：</span>
          </el-col>
        </el-row>
        <el-divider />
        <el-checkbox-group v-model="checkedFixedCustomColumns">
          <el-row>
            <el-col v-for="(val, key) in fixedDefaultLabelFormColumn" :key="key" :span="4">
              <el-checkbox :label="key">{{ val }}</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
        <el-divider />
        <el-checkbox-group v-model="checkOtherCustomColumns">
          <el-row>
            <el-col v-for="(val, key) in projectItemColumns" :key="key" :span="8">
              <el-checkbox :label="key">{{ val }}</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
        <el-divider />
        <el-checkbox-group v-model="checkedFixedTailCustomColumns">
          <el-row>
            <el-col v-for="(val, key) in fixedDefaultLabelFormTailColumn" :key="key" :span="4">
              <el-checkbox :label="key">{{ val }}</el-checkbox>
            </el-col>
          </el-row>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
                    <el-button @click="customColumnDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveStatisticsCheckedColumns">确 定</el-button>
                </span>
      </el-dialog>
    </div>
    <data-filter ref="dataFilter" :fields="projectItemList" @filter="dataFilterHandle" />
  </div>
</template>

<script>
  import _ from 'lodash'
  import DataFilter from './filter'
  import {queryFormProjectResByProjectId} from '@/api/form/formProject'
  import {queryFormProjectItemTableHeadResByProjectId} from '@/api/form/formProjectItem'
  import {queryFormProjectResultPageResList, deleteFormProjectResultById,saveFormProjectResult,updateFormProjectResult} from '@/api/form/formProjectResult'
  import { saveSystemCustom, querySystemCustomContentJsonByCustomKey } from "@/api/system/systemCustom";
  import FormResultAdd from './result/FormResultAdd'
  import FormResultEdit from './result/FormResultEdit'
  const uaParser = require('ua-parser-js')
  const ua = uaParser(navigator.userAgent)
  require('@/utils/form/utils/ut')
  // 头部固定标签
  const fixedDefaultFormColumn = ['serialNumber']
  const fixedDefaultLabelFormColumn = {serialNumber: '提交编号'}
  // 尾部固定标签
  const fixedDefaultFormTailColumn = ['createTime', 'updateTime','submitIp']
  const fixedDefaultLabelFormTailColumn = {createTime: '提交时间',updateTime: '更新时间', submitIp: '提交IP'}
  //默认查询参数
  let defaultQueryParams = {
    projectId: undefined,
    startTime: undefined,
    endTime: undefined,
    extComparisons: undefined,
    extParams: undefined,
    serialNumber: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: 'ProjectStatisticsList',
    props: {
      pId: {
        type: String,
        default: ''
      }
    },
    components: {
      DataFilter,
      FormResultAdd,
      FormResultEdit
    },
    data() {
      return {
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 日期范围
        dateRange: [],
        projectId: null,
        customFilterDialogVisible: false,
        customColumnDialogVisible: false,
        checkedFilterColumns: [],
        // 固定自定义列 如序号等
        fixedCustomColumns: fixedDefaultFormColumn,
        fixedFormTailColumns: fixedDefaultFormTailColumn,
        // 选中的
        checkedFixedCustomColumns: fixedDefaultFormColumn,
        fixedDefaultLabelFormColumn: fixedDefaultLabelFormColumn,
        checkedFixedTailCustomColumns: fixedDefaultFormTailColumn,
        fixedDefaultLabelFormTailColumn: fixedDefaultLabelFormTailColumn,
        // 自定义表单属性
        checkOtherCustomColumns: [],
        otherCustomColumns: [],
        //列信息
        columns: [],
        projectResultList: [],
        projectItemList: [],
        projectData: null,
        projectItemColumns: {},
        total: 0,
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //发起新增问卷配置
        projectConfig: {
          projectId: ''
        },
        //发起修改问卷配置
        projectUpdateConfig: {
          projectId: '',
          //隐藏提交按钮
         showBtns: true,
        },
        //预览界面
        projectViewConfig: {
          projectId: '',
          //隐藏提交按钮
          showBtns: false,
          //禁用
          disabledForm:true,
        },
        inActiveTime: 0,
        //发起问卷类型，是修改还是新增
        formResultWriteType:"addFormResult",
        //发起问卷弹窗标题
        formResultWriteTitle:"",
        //发起问卷弹窗
        formResultWriteOpen:false,
        //修改问卷弹窗传参ID
        updateFormResultId:"",
      }
    },
    mounted() {
      let pKey = this.$route.query.key
      this.projectId = pKey?pKey:this.pId
      this.queryParams.projectId = this.projectId
      this.queryProjectResult()
      this.queryProjectItems()
      //this.queryProject()
    }, methods: {
      renderHeader() {
        return (
          <i class="el-icon-setting" style="color:currentColor"
        onClick={() => this.customColumnDialogVisible = true}></i>
      )
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column) {
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryProjectResult()
      },

      queryProject() {
        queryFormProjectResByProjectId({"projectId":this.projectId}).then(res => {
          this.projectData = res.data
        })
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams = { ...defaultQueryParams }
        this.dateRange = []
        this.queryParams.projectId = this.projectId
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryProjectResult()
      },
      conditionFilterHandle() {
        this.$refs.dataFilter.showDialogHandle()
      },
      dataFilterHandle(params, comparisons) {
        this.queryParams.extParams = params?JSON.stringify(params):""
        this.queryParams.extComparisons = comparisons?JSON.stringify(comparisons):""
        this.queryProjectResult()
      },
      queryProjectResult() {
        queryFormProjectResultPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
          let {records, total } = res.data
          this.projectResultList = records
          this.total = total
        })
      },
      saveStatisticsCheckedColumns() {
        //BEG
        const settingJsonData =  {
          "fixedCustomColumns":this.checkedFixedCustomColumns,
          "otherCustomColumns":this.checkOtherCustomColumns,
          "fixedCustomTailColumns":this.checkedFixedTailCustomColumns
        };
        let projectId = this.projectId
        const settingData = {
          customKey: "formProjectResult"+projectId, content: JSON.stringify(settingJsonData)
        };
        saveSystemCustom(settingData).then(res => {
          if (res.errorCode === 0) {
            this.customColumnDialogVisible = false
            this.fixedCustomColumns = this.checkedFixedCustomColumns
            this.otherCustomColumns = this.checkOtherCustomColumns
            this.fixedFormTailColumns = this.checkedFixedTailCustomColumns
          }
        });
        //END
      },
      getDbCheckedColumns() {
        let projectId = this.projectId
        querySystemCustomContentJsonByCustomKey({customKey: "formProjectResult"+projectId}).then(res => {
          if (res&&res.data){
            const  settingData = JSON.parse(res.data);
            let {fixedCustomColumns, otherCustomColumns, fixedCustomTailColumns} = settingData
            if (fixedCustomColumns) {
              this.fixedCustomColumns = fixedCustomColumns
              this.checkedFixedCustomColumns = fixedCustomColumns
            }
            if (otherCustomColumns) {
              this.otherCustomColumns = otherCustomColumns
              this.checkOtherCustomColumns = otherCustomColumns
            }
            if (fixedCustomTailColumns) {
              this.fixedFormTailColumns = fixedCustomTailColumns
              this.checkedFixedTailCustomColumns = fixedCustomTailColumns
            }
          }
        });
      },



      //发起问卷记录保存功能
      saveFormProjectResult(data) {
        // 完成时间
        let inActiveTime = document.getElementById('inActiveTime').innerText
        let saveReq = {
          'completeTime': inActiveTime,
          'projectId': this.projectConfig.projectId,
          'submitOs': ua.os.name,
          'submitBrowser': ua.browser.name,
          'submitUa': ua,
          'originalData': data.formModel,
          'processData': data.labelFormModel
        }
        saveFormProjectResult(saveReq).then(response => {
          this.$modal.msgSuccess(response.message)
          this.formResultWriteOpen = false;
          this.queryProjectResult()
        });
      },


      /**弹出新增问卷弹窗*/
      handleAdd(){
        this.reset();
        this.formResultWriteOpen = true;
        this.projectConfig.projectId = this.projectId;
        this.formResultWriteType = "addFormResult";
        this.formResultWriteTitle = "新增记录";
      },

      /**弹出修改问卷记录弹出*/
      handleUpdate(row){
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        const id = row.id
        this.projectUpdateConfig.projectId = id
        this.formResultWriteOpen = true;
        this.formResultWriteType = "editFormResult";
        this.updateFormResultId = id;
        this.formResultWriteTitle = "修改记录";
      },

      /**预览记录详情*/
      handleView(row){
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.projectViewConfig.projectId = row.id
        this.formResultWriteOpen = true;
        this.formResultWriteType = "viewFormResult";
        this.formResultWriteTitle = "记录详情";
      },

      // 表单重置
      reset() {
        this.inActiveTime = 0;
      },

      //发起问卷记录修改功能
      updateFormProjectResult(data) {
        // 完成时间
        let inActiveTime = document.getElementById('inActiveTime').innerText
        let saveReq = {
          'completeTime': inActiveTime,
          'id': this.updateFormResultId,
          'submitOs': ua.os.name,
          'submitBrowser': ua.browser.name,
          'submitUa': ua,
          'originalData': data.formModel,
          'processData': data.labelFormModel
        }
        updateFormProjectResult(saveReq).then(response => {
          this.$modal.msgSuccess(response.message)
          this.formResultWriteOpen = false;
          this.queryProjectResult()
        });
      },
      //预览虚拟填提示
      viewFormProjectResult(data) {

      },

      /** 是否删除 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认把所选记录彻底删除?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const id={id:row.id}
          return deleteFormProjectResultById(id);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryProjectResult();
        }).catch(function() {});
      },

      queryProjectItems() {
        queryFormProjectItemTableHeadResByProjectId({"projectId":this.projectId}).then(res => {
          if (res.data) {
            res.data.map(item => {
              _.set(this.projectItemColumns, `field${item.formItemId}`, item.label)
            })
            this.projectItemList = res.data
            this.getDbCheckedColumns()
          }
        })
      }
    }

  }
</script>

<style scoped>
  .statistics-container {
    margin-top: 20px;
    width: 100%;
    height: 100%;
  }

  .custom-col-container >>> .el-checkbox__label {
    width: 200px;
    min-height: 25px;
    line-height: 25px;
    vertical-align: middle;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .result-table-view {
/*    width: 95%;
    min-height: 75vh;*/
    margin: 6px auto;
  }

  .detail-container {
    padding: 20px;
    height: 100% !important;
  }

  .filter-table-view {
    width: 95%;
    margin: 0 auto;
  }

  ::v-deep .el-icon-setting {
    font-size: 24px;
    line-height: 25px;
    color: white;
  }

  ::v-deep .data-table-header .cell {
    text-overflow: ellipsis !important;
    white-space: nowrap !important;
  }

  /* 1.显示滚动条：当内容超出容器的时候，可以拖动： */
  ::v-deep .el-drawer__body {
    overflow: auto;

    /* overflow-x: auto; */
  }

  /* 2.隐藏滚动条，太丑了 */
  ::v-deep .el-drawer__container ::-webkit-scrollbar {
    display: none;
  }

</style>
